package com.ruoyi.teaching.service.impl;

import java.util.List;
import com.ruoyi.common.core.utils.DateUtils;
import com.vladsch.flexmark.util.ast.Node;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.teaching.mapper.YaKnowledgePointsMapper;
import com.ruoyi.teaching.domain.YaKnowledgePoints;
import com.ruoyi.teaching.service.IYaKnowledgePointsService;
import org.springframework.web.multipart.MultipartFile;
import com.vladsch.flexmark.ast.Heading;
import com.vladsch.flexmark.parser.Parser;
import com.vladsch.flexmark.util.options.MutableDataSet;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

/**
 * 知识点Service业务层处理
 * 
 * @author ZBX
 * @date 2025-03-20
 */
@Service
public class YaKnowledgePointsServiceImpl implements IYaKnowledgePointsService 
{
    @Autowired
    private YaKnowledgePointsMapper yaKnowledgePointsMapper;

    /**
     * 查询知识点
     * 
     * @param id 知识点主键
     * @return 知识点
     */
    @Override
    public YaKnowledgePoints selectYaKnowledgePointsById(Long id)
    {
        return yaKnowledgePointsMapper.selectYaKnowledgePointsById(id);
    }

    /**
     * 查询知识点列表
     * 
     * @param yaKnowledgePoints 知识点
     * @return 知识点
     */
    @Override
    public List<YaKnowledgePoints> selectYaKnowledgePointsList(YaKnowledgePoints yaKnowledgePoints)
    {
        return yaKnowledgePointsMapper.selectYaKnowledgePointsList(yaKnowledgePoints);
    }

    /**
     * 新增知识点
     * 
     * @param yaKnowledgePoints 知识点
     * @return 结果
     */
    @Override
    public int insertYaKnowledgePoints(YaKnowledgePoints yaKnowledgePoints)
    {
        yaKnowledgePoints.setCreateTime(DateUtils.getNowDate());
        return yaKnowledgePointsMapper.insertYaKnowledgePoints(yaKnowledgePoints);
    }

    /**
     * 修改知识点
     * 
     * @param yaKnowledgePoints 知识点
     * @return 结果
     */
    @Override
    public int updateYaKnowledgePoints(YaKnowledgePoints yaKnowledgePoints)
    {
        yaKnowledgePoints.setUpdateTime(DateUtils.getNowDate());
        return yaKnowledgePointsMapper.updateYaKnowledgePoints(yaKnowledgePoints);
    }

    /**
     * 批量删除知识点
     * 
     * @param ids 需要删除的知识点主键
     * @return 结果
     */
    @Override
    public int deleteYaKnowledgePointsByIds(Long[] ids)
    {
        return yaKnowledgePointsMapper.deleteYaKnowledgePointsByIds(ids);
    }

    /**
     * 删除知识点信息
     * 
     * @param id 知识点主键
     * @return 结果
     */
    @Override
    public int deleteYaKnowledgePointsById(Long id)
    {
        return yaKnowledgePointsMapper.deleteYaKnowledgePointsById(id);
    }


    /**
     * 批量导入知识点
     * @param file
     * @return
     */
    @Override
    public Map<String, Object> parseAndSave(MultipartFile file) {
        Map<String, Object> result = new HashMap<>();
        List<String> addedKnowledgePoints = new ArrayList<>();
        List<String> updatedKnowledgePoints = new ArrayList<>();

        // 1. 检查文件是否为空
        if (file.isEmpty()) {
            result.put("message", "上传的文件为空");
            return result;
        }

        // 2. 检查是否为.md文件
        if (!file.getOriginalFilename().endsWith(".md")) {
            result.put("message", "上传的文件不是Markdown文件");
            return result;
        }

        try {
            // 3. 读取文件内容到String
            StringBuilder content = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                if (line != null && !line.trim().isEmpty() && !line.equals("---")) {
                    content.append(line).append("\n");
                }
            }
            reader.close();

            // 4. 配置Flexmark解析器
            MutableDataSet options = new MutableDataSet();
            Parser parser = Parser.builder(options).build();

            // 5. 解析MarkDown内容到Node对象
            Node document = parser.parse(content.toString());

            // 6. 初始化知识点列表
            List<YaKnowledgePoints> knowledgePoints = new ArrayList<>();
            YaKnowledgePoints currentKnowledgePoint = null;
            StringBuilder tempText = new StringBuilder();

            // 7. 遍历Node节点
            String lastLevel3Heading = null;
            for (Node node : document.getChildren()) {
                if (node instanceof Heading) {
                    Heading heading = (Heading) node;
                    String headingText = cleanText(heading.getText().toString());
                    if (heading.getLevel() == 2) {
                        processLastKnowledgePoint(currentKnowledgePoint, lastLevel3Heading, tempText, knowledgePoints);
                        currentKnowledgePoint = new YaKnowledgePoints();
                        currentKnowledgePoint.setName(headingText);
                        tempText.setLength(0);
                        lastLevel3Heading = null;
                    } else if (heading.getLevel() == 3) {
                        processLastKnowledgePoint(currentKnowledgePoint, lastLevel3Heading, tempText, null);
                        tempText.setLength(0);
                        lastLevel3Heading = headingText;
                    }
                } else {
                    tempText.append(cleanText(node.getChars().toString())).append("\n");
                }
            }
            processLastKnowledgePoint(currentKnowledgePoint, lastLevel3Heading, tempText, knowledgePoints);

            // 8. 过滤掉what为空的知识点
            knowledgePoints.removeIf(point -> point.getWhat() == null || point.getWhat().isEmpty());

            // 9. 遍历知识点列表，根据是否存在进行更新或新增
            for (YaKnowledgePoints point : knowledgePoints) {
                YaKnowledgePoints existingPoint = yaKnowledgePointsMapper.selectYaKnowledgePointsByName(point.getName());
                if (existingPoint != null) {
                    point.setId(existingPoint.getId());
                    yaKnowledgePointsMapper.updateYaKnowledgePoints(point);
                    updatedKnowledgePoints.add(point.getName());
                } else {
                    yaKnowledgePointsMapper.insertYaKnowledgePoints(point);
                    addedKnowledgePoints.add(point.getName());
                }
            }

            result.put("newList", addedKnowledgePoints);
            result.put("updateList", updatedKnowledgePoints);
            result.put("message", "处理成功");
        } catch (IOException e) {
            result.put("message", "文件读取失败: " + e.getMessage());
        }

        return result;
    }



    /**
     * 处理最后一个三级标签的内容
     * @param currentKnowledgePoint 当前知识点
     * @param lastLevel3Heading 最后一个三级标签
     * @param tempText 临时文本
     *
     */
    private void processLastKnowledgePoint(YaKnowledgePoints currentKnowledgePoint, String lastLevel3Heading, StringBuilder tempText, List<YaKnowledgePoints> knowledgePoints) {
        if (currentKnowledgePoint != null && lastLevel3Heading != null) {
            String text = tempText.toString().trim();
            switch (lastLevel3Heading) {
                case "What":
                    currentKnowledgePoint.setWhat(text);
                    break;
                case "Why":
                    currentKnowledgePoint.setWhy(text);
                    break;
                case "How":
                    currentKnowledgePoint.setHow(text);
                    break;
                case "When":
                    currentKnowledgePoint.setWhenUse(text);
                    break;
                case "总结":
                    currentKnowledgePoint.setSummary(text);
                    break;
                case "高频面试题":
                    currentKnowledgePoint.setHighInterviewQuestion(text);
                    break;
            }
            if (knowledgePoints != null) {
                knowledgePoints.add(currentKnowledgePoint);
            }
        }
    }

    /**
     * 去除文本中的特殊字符
     * @param text 原始文本
     * @return 处理后的文本
     */
    private String cleanText(String text) {
        text = text.replaceAll("<[^>]*>", "");
        text = text.replaceAll("\\+ ", "");
        text = text.replaceAll("\\+ \\*\\*", "");
        text = text.replaceAll("- \\*\\*", "");
        text = text.replaceAll("\\*\\*", "");
        text = text.replaceAll("<font[^>]*>", "");
        text = text.replaceAll("</font>", "");
        text = text.replaceAll("```", "");
        text = text.replaceAll("\\s*```", "");
        text = text.replaceAll("\\s+", " ").trim();
        text = text.replaceAll("[^a-zA-Z0-9\\u4e00-\\u9fa5]", "");
        return text;
    }

}
